package cn.c4ad.voa;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.text.TextUtils;

public class VoaContentProvider extends ContentProvider {
	private static String DATABASE_NAME = "voa.db";
	private static final int DATABASE_VERSION = 1;

	public static final String TABLE_ARTICAL = "artical";
	public static final String TABLE_PLAY = "play";

	public static final String ID = "_id";
	public static final String TYPE = "type";
	public static final String URL = "url";
	public static final String TITLE = "title";
	public static final String HEAD = "head";
	public static final String CONTENT = "content";
	public static final String MP3URL = "mp3url";
	public static final String DOWNLOAD_ID = "download_id";
	public static final String DOWNLOAD_STATE = "download_state";

	public static final String ARTICAL_ID = "artical_id";
	public static final String PLAY_TIME = "play_time";

	public static final int DOWNLOAD_STATE_NULL = 0;
	public static final int DOWNLOAD_STATE_COMPLETED_TEXT = 1;
	public static final int DOWNLOAD_STATE_LOADING_MP3 = 2;
	public static final int DOWNLOAD_STATE_COMPLETED_ALL = 3;

	public static final int TYPE_SPECIAL = 0;
	public static final int TYPE_STANDARD = 1;

	public static final String AUTHORITY = "cn.c4ad.voa.content";
	public static final Uri ARTICAL_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_ARTICAL);
	public static final Uri PLAY_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_PLAY);

	private static final int CODE_ARTICAL = 1;
	private static final int CODE_ARTICAL_ITEM = 2;

	private static final int CODE_PLAY = 3;

	private static final String DIC_DATABASE_NAME = "dictionary.db";
	private static final String DIC_DATABASE_TABLE = "t_words";
	private static final int DIC_DATABASE_VERSION = 1;
	private static final String DIC_COLUMN_EN = "english";
	private static final String DIC_COLUMN_CN = "chinese";

	public static final void checkDictionaryDatabase(Context context) {
		DicDatabaseHelper dicDatabaseHelper = new DicDatabaseHelper(context);
		SQLiteDatabase database = dicDatabaseHelper.getReadableDatabase();
		String sql = "SELECT COUNT(*) FROM " + DIC_DATABASE_TABLE;
		SQLiteStatement statement = database.compileStatement(sql);
		long count = statement.simpleQueryForLong();
		if (count > 0) {
			return;
		}

		InputStream is = null;
		OutputStream os = null;

		try {
			is = context.getAssets().open(DIC_DATABASE_NAME);
			os = new FileOutputStream(
					context.getDatabasePath(DIC_DATABASE_NAME));
			byte[] buffer = new byte[1024];
			int length;
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
			os.flush();
		} catch (Exception e) {

		} finally {
			try {
				is.close();
			} catch (Exception e) {
			}

			try {
				os.close();
			} catch (Exception e) {
			}
		}
	}

	public static final String checkDictionary(Context context, String word) {
		String meaning = null;
		DicDatabaseHelper dicDatabaseHelper = new DicDatabaseHelper(context);
		SQLiteDatabase database = dicDatabaseHelper.getReadableDatabase();
		Cursor cursor = database.query(DIC_DATABASE_TABLE,
				new String[] { DIC_COLUMN_CN }, DIC_COLUMN_EN + "=? COLLATE NOCASE",
				new String[] { word }, null, null, null);
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				meaning = cursor
						.getString(cursor.getColumnIndex(DIC_COLUMN_CN));
			}
			cursor.close();
		}
		return meaning;
	}

	private static class DicDatabaseHelper extends SQLiteOpenHelper {
		public DicDatabaseHelper(Context context) {
			super(context, DIC_DATABASE_NAME, null, DIC_DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE  IF NOT EXISTS " + DIC_DATABASE_TABLE
					+ " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT" + ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

		}
	}

	private class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE  IF NOT EXISTS " + TABLE_ARTICAL + " ("
					+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TYPE
					+ " INTEGER DEFAULT 0," + URL + " TEXT," + TITLE + " TEXT,"
					+ HEAD + " TEXT," + CONTENT + " TEXT," + MP3URL + " TEXT,"
					+ DOWNLOAD_ID + " INTEGER DEFAULT 0," + DOWNLOAD_STATE
					+ " INTEGER DEFAULT 0" + ");");

			db.execSQL("CREATE TABLE  IF NOT EXISTS " + TABLE_PLAY + " (" + ID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT," + ARTICAL_ID
					+ " INTEGER," + PLAY_TIME + " INTEGER" + ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

		}
	}

	private static final UriMatcher mUriMatcher;
	static {
		mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		mUriMatcher.addURI(AUTHORITY, TABLE_ARTICAL, CODE_ARTICAL);
		mUriMatcher.addURI(AUTHORITY, TABLE_ARTICAL + "/#", CODE_ARTICAL_ITEM);

		mUriMatcher.addURI(AUTHORITY, TABLE_PLAY, CODE_PLAY);
	}

	private ContentResolver mContentResolver;
	private DatabaseHelper mDatabaseHelper;

	@Override
	public boolean onCreate() {
		Context context = getContext();
		mContentResolver = context.getContentResolver();
		mDatabaseHelper = new DatabaseHelper(context);
		return true;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		String table = null;

		switch (mUriMatcher.match(uri)) {
		case CODE_ARTICAL:
			table = TABLE_ARTICAL;
			break;

		case CODE_PLAY:
			table = TABLE_PLAY;
			break;

		default:
			throw new IllegalArgumentException("Error Uri: " + uri);
		}

		SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
		long id = database.insert(table, null, values);
		if (id < 0) {
			throw new SQLiteException("Unable to insert " + values + " for "
					+ uri);
		}

		Uri itemUri = ContentUris.withAppendedId(uri, id);
		mContentResolver.notifyChange(itemUri, null);

		return itemUri;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		switch (mUriMatcher.match(uri)) {
		case CODE_ARTICAL:
			sqlBuilder.setTables(TABLE_ARTICAL);
			break;

		case CODE_ARTICAL_ITEM:
			sqlBuilder.setTables(TABLE_ARTICAL);
			String id = uri.getPathSegments().get(1);
			sqlBuilder.appendWhere(ID + "=" + id);
			break;

		case CODE_PLAY:
			sqlBuilder.setTables(TABLE_PLAY);
			break;

		default:
			throw new IllegalArgumentException("Error Uri: " + uri);
		}

		SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
		Cursor cursor = sqlBuilder.query(database, projection, selection,
				selectionArgs, null, null, sortOrder, null);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
		int count = 0;
		switch (mUriMatcher.match(uri)) {
		case CODE_ARTICAL:
			count = database.update(TABLE_ARTICAL, values, selection,
					selectionArgs);
			break;

		case CODE_ARTICAL_ITEM:
			String id = uri.getPathSegments().get(1);
			count = database.update(TABLE_ARTICAL, values, ID
					+ "="
					+ id
					+ (!TextUtils.isEmpty(selection) ? " and (" + selection
							+ ')' : ""), selectionArgs);
			break;

		case CODE_PLAY:
			count = database.update(TABLE_PLAY, values, selection,
					selectionArgs);
			break;

		default:
			throw new IllegalArgumentException("Error Uri: " + uri);
		}
		mContentResolver.notifyChange(uri, null);
		return count;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
		int count = 0;
		switch (mUriMatcher.match(uri)) {
		case CODE_ARTICAL:
			count = database.delete(TABLE_ARTICAL, selection, selectionArgs);
			break;

		case CODE_ARTICAL_ITEM:
			String id = uri.getPathSegments().get(1);
			count = database.delete(TABLE_ARTICAL,
					ID
							+ "="
							+ id
							+ (!TextUtils.isEmpty(selection) ? " and ("
									+ selection + ')' : ""), selectionArgs);
			break;

		case CODE_PLAY:
			count = database.delete(TABLE_PLAY, selection, selectionArgs);
			break;

		default:
			throw new IllegalArgumentException("Error Uri: " + uri);
		}
		mContentResolver.notifyChange(uri, null);
		return count;
	}
}
